package com.team.sns.web;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.struts2.interceptor.SessionAware;

import com.team.sns.entities.MsgInfo;
import com.team.sns.entities.User;
import com.team.sns.entities.UserMsgIndex;
import com.team.sns.services.MessageService;
import com.team.sns.services.UserFollowService;
import com.team.sns.services.UserService;


public class MessageAction extends BasicAction implements SessionAware{
	
	private Map session;
	
	private MsgInfo info;
	
	private User user;
	
	@Resource(name = "userService")
	private UserService userService;
	@Resource
	private UserFollowService userFollowService;
	@Resource
	private MessageService messageService;

	
	public String createMessage(){
		//消息元数据
		info.setCreateTime(new Date().toString());
		info.setType(0);
		this.messageService.save(info);
		
		//发布的消息数量+1
		user.setMsg_count(user.getMsg_count() + 1);
		this.userService.update(user);
		
		//消息索引表
		UserMsgIndex index = new UserMsgIndex();
		index.setCreateTime(new Date().toString());
		index.setAuthorId(user.getId());
		index.setUserId(user.getId());
		index.setMsgId(info.getId());
		this.messageService.saveMsgIndex(index);
		
		//push模式，为所有关注的对象插入一条记录
		List<Integer> lst = this.userFollowService.getFollowUserIds(user.getId());//取出关注它的所有用户id
		for(Integer userId : lst){
			UserMsgIndex userMsgIndex = new UserMsgIndex();
			userMsgIndex.setAuthorId(user.getId());
			userMsgIndex.setMsgId(info.getId());
			userMsgIndex.setUserId(userId);
			userMsgIndex.setCreateTime(new Date().toString());
			this.messageService.saveMsgIndex(userMsgIndex);
		}
		
		return "";
	}
	
	public void showMessage(){
		
	}
	
	public void setSession(Map<String, Object> arg0) {
		this.session = arg0;
	}
	
	public MsgInfo getInfo() {
		return info;
	}

	public void setInfo(MsgInfo info) {
		this.info = info;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}


}
